# -*- coding: utf-8 -*-
import sys
sys.path.append("../..")
from db.mysql import MysqlClient
import asyncio, aiohttp
from itertools import product
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode
import json
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "旅行人身意外伤害保险"

    # 生成数据
    def genProductInfo(self):
        plan = {
            "planA": {
                "days": ["1d", "3d", "7d", "10d", "15d", "21d", "1m"],
                "people_count": ["1"],
                "accident_death": ["50000", "100000", "200000", "300000", "400000", "500000"],
                "burial_fee": ["0", "2000", "10000", "20000"],
                "accident_medical": ["0", "2000", "10000", "20000", "50000"],
                "travel_place": ["境内"]
            },
            "planB": {
                "days": ["1d", "3d", "7d", "10d", "15d", "21d", "1m"],
                "people_count": ["1"],
                "accident_death": ["50000", "100000", "200000", "300000", "400000", "500000"],
                "burial_fee": ["0", "2000", "10000", "20000"],
                "accident_medical": [""],
                "travel_place": ["境外"]
            }

        }

        for k in plan:
            for v in product(plan[k]["days"], plan[k]["people_count"], plan[k]["accident_death"], plan[k]["burial_fee"],
                             plan[k]["accident_medical"], plan[k]["travel_place"]):
                data = Helper.formatProductInfo(plan[k], v)
                yield data

    # 异步爬虫
    async def requestJson(self, dt):

        params = '''
        productCode: 6115_lx_615_v3
        riskCode: 6115
        subDataSource: 10001000
        dataSourse: 
        thirdAppId: fff4fbe4c3c31950ba0517054wxid01
        thirdUserFlag: 0
        mobileBanImg: /css/notCar/weixin/wechat/images/title/6115_lx_615.png
        policy.destination: 中国China
        policy.destinationCode: china
        policy.startDate: 2020-04-30
        policy.endDate: 2020-05-04
        itemKind[0].type: Y11004
        itemKind[0].kindCode: 611500_0001
        itemKind[0].kindName: 意外伤害保障
        itemKind[0].rate: 0.0600
        itemKind[0].premiums: 6
        itemKind[1].type: Y11004
        itemKind[1].kindCode: 611500_0003
        itemKind[1].kindName: 丧葬保障
        itemKind[1].rate: 
        itemKind[1].premiums: 0
        itemKind[2].type: N11004
        itemKind[2].kindCode: 611502_0008
        itemKind[2].kindName: 意外医疗保障
        itemKind[2].rate: 
        itemKind[2].premiums: 0
        premiumPrice: 6.00
        insuredPrice: 100000.00
        policy.areaFlag: 1
        planCode: 6115_lx_6115_v3
        itemKind[0].insured: 100000
        itemKind[1].insured: 
        itemKind[2].insured: 
        '''
        data = Helper.perfectJson(params)
        data["policy.destination"] = "中国China" if dt["travel_place"] == "境内" else "波斯尼亚和黑塞哥维那"
        data["itemKind[0].insured"] = dt["accident_death"]
        data["itemKind[1].insured"] = "" if dt["burial_fee"] == "0" else dt["burial_fee"]
        data["itemKind[2].insured"] = "" if dt["accident_medical"] == "0" else dt["accident_medical"]
        init = 0

        if dt["days"] == "1d":
            endDateNumber = "2020-04-30"
        elif dt["days"] == "1m":
            endDateNumber = "2020-05-31"
        else:

            endDateNumber = "2020-05-0{0}".format(str(init + int(dt["days"].replace("d", "")))) if int(
                dt["days"].replace("d", "")) < 10 else "2020-05-{0}".format(
                str(init + int(dt["days"].replace("d", ""))))
        data["policy.endDate"] = endDateNumber
        payload = urlencode(data).replace("+","")
        async with semaphore:
            async with aiohttp.ClientSession() as session:
                async with session.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                        data=payload) as resp:
                    res = await resp.text()
                    if "premiums" in res:
                        prices = [data["premiums"] for data in json.loads( res )]
                        price = Helper.decimalParse( sum( prices ))
                        data = {
                            "name":self.name,
                            "company":"鼎和保险",
                            "price":price
                        }
                        data.update( dt )
                        Helper.mergeTable( self.name,self.mysql,data )

                    else:
                        pass


    def asyncTask(self):

        global semaphore

        semaphore = asyncio.Semaphore(10)

        tasks = [self.requestJson(data) for data in self.genProductInfo()]

        event_loop = asyncio.get_event_loop()

        event_loop.run_until_complete(asyncio.gather(*tasks))

        event_loop.close()
